<?php
declare(strict_types=1);

namespace App\Services\Business;


use App\Models\MainDB\GiveGift;
use App\Models\MainDB\RoomNaming;
use App\Models\MainDB\UserDevice;
use App\Models\MainDB\UserRoom;
use App\Services\Tools\AmapService;
use App\Services\Tools\PushService;
use Illuminate\Support\Facades\DB;

class UserService
{
    /**
     * 给所有用户填充所在地区
     * @return mixed
     * @throws \App\Exceptions\BasicException
     */
    public function autoSearchUserRegion()
    {
        $subQuery = UserDevice::query()->orderBy('id', 'DESC')->limit(999999);
        $userDevices = DB::table(DB::raw("({$subQuery->toSql()}) as sub "))
            ->select(['user_id', 'ip'])
            ->groupBy('user_id')
            ->mergeBindings($subQuery->getQuery())
            ->get()
            ->toArray();
        $count = 0;
        foreach ($userDevices as $userDevice) {
            $ip = $userDevice->ip;
            $res = (new AmapService())->getRegionByIp($ip);
            if ($res->status == 1) {
                if (!empty($res->city) && !empty($res->adcode)) {
                    app('redis')->sadd('city:' . $res->adcode, [$userDevice->user_id]); // 同一个城市存入用户ID
                }
            }
            $count++;
        }
        return $count;
    }


    public function createNaming()
    {
        $time = time() - 6 * 3600;
        $date = date('Y-m-d H:i:s', time());
        $room = UserRoom::query()->get();
        $data = [];
        foreach ($room as $value) {
            $price = GiveGift::query()
                ->select(['user_id', DB::raw('SUM(total_price) as total'), DB::raw('RANK() OVER (ORDER BY SUM(total_price) DESC) as rankInfo')])
                ->where('add_time', '>', $time)
                ->where('room_id', $value['id'])->groupBy(['user_id'])->get()->toArray();
            foreach ($price as $v) {
                $data[] = [
                    'room_id'       => $value['id'],
                    'user_id'       => $v['user_id'],
                    'rank'          => $v['rankInfo'],
                    'score'         => $v['total'],
                    'statistics_at' => $date,
                ];


            }
            (new PushService(0, $value['id']))->roomNamingUser(10);
        }
        RoomNaming::query()->insert($data);

    }

}